using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using ImageServer2.Models;

namespace ImageServer2.Controllers;

public class HomeController(IWebHostEnvironment webHostEnvironment) : Controller {

    public IActionResult Index() {
        return View();
    }

    public IActionResult Privacy() {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error() {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
    
    public async Task<IActionResult> ImageUpload(IFormFile? image) {
        if (image == null || image.Length == 0) {
            return BadRequest("file not selected");
        }
        var fileName = Guid.NewGuid() + Path.GetExtension(image.FileName);
        var filePath = Path.Combine(webHostEnvironment.WebRootPath,"images",fileName);
        await using var stream = System.IO.File.Create(filePath);
        await image.CopyToAsync(stream);
        return Ok(Path.Combine("images", fileName));
    }
}